from dataclasses import dataclass

@dataclass
class CausalityEdge:
    """
    因果关系边，表示指标之间的因果关系
    """
    
    def __init__(
        self, 
        cause_pod: str, 
        cause_metric: str, 
        effect_pod: str, 
        effect_metric: str, 
        strength: float, 
        p_value: float, 
        time_lag: int,
        method: str = "pcmci_plus", 
        from_entity_type: str = "container", 
        to_entity_type: str = "container",
        anomaly_phase: str = "unknown"  # 新增属性，标记是故障前(pre_anomaly)还是故障后(post_anomaly)的因果关系
    ):
        """
        初始化因果关系边
        
        参数:
            cause_pod: 原因Pod/实体ID
            cause_metric: 原因指标名称
            effect_pod: 结果Pod/实体ID
            effect_metric: 结果指标名称
            strength: 因果强度
            p_value: P值（统计显著性）
            time_lag: 时间滞后
            method: 使用的方法
            from_entity_type: 原因实体类型
            to_entity_type: 结果实体类型
            anomaly_phase: 标记该边是故障前(pre_anomaly)还是故障后(post_anomaly)的因果关系
        """
        self.cause_pod = cause_pod
        self.cause_metric = cause_metric
        self.effect_pod = effect_pod
        self.effect_metric = effect_metric
        self.strength = strength
        self.p_value = p_value
        self.time_lag = time_lag
        self.method = method
        self.from_entity_type = from_entity_type
        self.to_entity_type = to_entity_type
        self.anomaly_phase = anomaly_phase  # 新增属性
        
    def __str__(self):
        """返回边的字符串表示"""
        return (f"({self.cause_pod}:{self.cause_metric}) -> ({self.effect_pod}:{self.effect_metric}) "
                f"[strength={self.strength:.4f}, p_value={self.p_value:.4f}, lag={self.time_lag}, "
                f"phase={self.anomaly_phase}]")
    
    def __repr__(self):
        """返回边的代码表示"""
        return f"CausalityEdge({self.cause_pod}, {self.cause_metric}, {self.effect_pod}, {self.effect_metric}, phase={self.anomaly_phase})"
    
    def to_dict(self):
        """
        将因果关系边转换为字典格式，便于序列化
        
        返回:
            包含所有属性的字典
        """
        return {
            "cause_pod": self.cause_pod,
            "cause_metric": self.cause_metric,
            "effect_pod": self.effect_pod,
            "effect_metric": self.effect_metric,
            "strength": float(self.strength),  # 确保数值类型正确
            "p_value": float(self.p_value),
            "time_lag": int(self.time_lag),
            "method": self.method,
            "from_entity_type": self.from_entity_type,
            "to_entity_type": self.to_entity_type,
            "anomaly_phase": self.anomaly_phase
        }
